package com.meida.zuul.controller;

import com.meida.zuul.configuration.ApiProperties;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author: zyf
 * @date: 2018/11/5 16:33
 * @description:
 */
@Controller
public class IndexController {
    @Autowired
    private ApiProperties apiProperties;


    @Value("${spring.application.name}")
    private String serviceId;

    @GetMapping("/")
    public String index() {
        if (apiProperties.getApiDebug()) {
            return "redirect:doc";
        }
        return "index";
    }

    @GetMapping("/doc")
    public void doc(HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = null;
        InputStream inputStream = null;
        Reader reader = null;
        try {
            out = response.getWriter();
            String fileName = "classpath:/META-INF/resources/doc.html";
            ResourceLoader resourceLoader = new DefaultResourceLoader();
            inputStream = resourceLoader.getResource(fileName).getInputStream();
            //将文件输出为文本
            char[] buf = new char[2048];
            reader = new InputStreamReader(inputStream, "UTF-8");
            StringBuilder docHtml = new StringBuilder();
            while (true) {
                int n = reader.read(buf);
                if (n < 0)
                    break;
                docHtml.append(buf, 0, n);
            }
            //追加参数说明代码
            Document docHtmlDocument = Jsoup.parse(docHtml.toString());

            Elements docHtmlBodys = docHtmlDocument.select("body");
            // docHtmlBodys.append("<script src=\"static/sg/swaggerplus.js\"></script>");
            out.println(docHtmlDocument.toString());
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (reader != null) {
                reader.close();
            }
        }

    }

    @GetMapping("/test")
    public String test(HttpServletResponse response) {
        return "index";
    }

    @GetMapping("/apple-app-site-association")
    public String site(HttpServletResponse response) {
        return "index";
    }

}